import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import Login from '../views/Login.vue'
import Register from '../views/Register.vue'
import NotFound from '../views/NotFound.vue'
import Student from '../views/Student.vue'
import MyClass from '../views/student_views/MyClass.vue'
import web_axios from "../axios";

const routes = [
    {
        path: '/student/:page?',
        name: 'Student',
        component: Student,
        meta: {
            title: '学生',
            type: 'login'
        },
        children: [
            // 当 /user/:id 匹配成功
            // UserHome 将被渲染到 User 的 <router-view> 内部
            {
                path: 'myclass',
                component: MyClass,
                meta: {
                    title: '我的班级',
                    type: 'login'
                },
            },
            {
                path: '',
                component: NotFound,
            },
        ],
    },
    {
        path: '/login',
        name: 'Login',
        component: Login,
        meta: {
            title: '登录',
            type: ''
        }
    },
    {
        path: '/register',
        name: 'Register',
        component: Register,
        meta: {
            title: '注册',
            type: ''
        }
    },
    {
        path: '/:pathMatch(.*)*',
        name: 'NotFound',
        component: NotFound,
        meta: {
            title: '糟糕，找不到内容！',
            type: ''
        }
    },
]

const router = createRouter({
    history: createWebHistory(process.env.BASE_URL),
    routes
})

// show page titles
const DEFAULT_TITLE = "BiuBiu 考试系统";
router.afterEach((to, from) => {
    // document.title = to.meta.title || DEFAULT_TITLE;
    if (to.meta.title) {
        document.title = "BiuBiu 考试系统 - " + to.meta.title
    } else {
        document.title = "BiuBiu 考试系统"
    }

});

router.beforeEach((to, from, next) => {
    const type = to.meta.type
    // 判断该路由是否需要登录权限
    if (type === 'login') {
        web_axios.post("/isLogin").then((value) => {
            if (value.data.code === 200 && value.data.msg === "已登录！") {
                next()
            } else {
                next({
                    name: 'Login',
                    query: {
                        redirect: to.fullPath//当前页面的地址
                    }
                })
            }
        }).catch((err) => {
            console.log(err);
            next({
                name: 'Login',
                query: {
                    redirect: to.fullPath//当前页面的地址
                }
            })
        })
    } else {
        next()  // 确保一定要有next()被调用
    }
})

export default router
